<template>
  <div>
    <label v-if="label">{{ label }}</label>
    <slot></slot>
    <label style="color:red;" v-if="error">{{error}}</label>
  </div>
</template>

<script>
import Schema from "async-validator";

export default {
  name: "f-form-item",
  inject: {
    form: {
      from: "form"
    }
  },
  props: {
    label: {
      type: String,
      default: ""
    },
    prop: {
      type: String
    }
  },
  data() {
    return {
      error: ""
    };
  },
  methods: {
    validate() {
      const rules = this.form.rules[this.prop];
      const value = this.form.modal[this.prop];

      const desc = { [this.prop]: rules };

      const schema = new Schema(desc);
      return schema.validate({ [this.prop]: value }, errors => {
        if (errors) {
          this.error = errors[0].message;
        } else {
          this.error = "";
        }
      });
    }
  },
  mounted() {
    this.$on("validate", () => {
      this.validate();
    });
  }
};
</script>

<style lang="scss" scoped>
</style>